$(function(){
	savePrevPageUrl(prevPageUrl);
	$("#back").on("click", function(){
		$.go(getPrevPageUrl());
	});
	var cartList = $("#cartList");
	//编辑
	cartList.on("click", ".cart-edit", function(){
		$(this).parent().next(".cart-edit-panel").show().find(".amount-input").data("inputData","{}").trigger("change",true);
	})
	//删除
	.on("click", ".cart-del, .cart-dis-del", function(){
		var _this = this;
		$.confirm("确认删除本商品？", function(){
			cartProccess(cartDelUrl, {
				cartIds: $(_this).closest("li").attr("data-cart-id"),
				selectedIds:getSelected()
			}, function(data){
				if(data.flag){
					$(_this).closest("li").remove();
					cartList.children("li").size()==0&&$("#cartListWrap, #cartSettle").hide().siblings("#cartEmpty").show();
					setSettle(data);
				}else{
					$.alert(data.msg);
				}
			});
		});
	})
	//编辑完成
	.on("click", ".cart-comp", function(){
		$(this).closest(".cart-edit-panel").hide();
	})
	//单选
	.on("click", ".cart-select", function(){
		var li = $(this).parent();
		if(li.is(".selected")){
			li.toggleClass("selected");
			selectedSum(getSelected());
		}else{
			var cartIds = getSelected()+","+li.attr("data-cart-id");
			selectedSum(cartIds, function(data){
				li.toggleClass("selected")
			});
		}
	});
	//全选
	$("#selectAll").on("click", function(){
		var _this = this;
		if($(this).is(".selected")){
			$(_this).removeClass("selected");
			cartList.children("li").removeClass("selected");
			resetCart();
		}else{
			var selectIds = cartList.children("li").not(".disabled").map(function(){return $(this).attr("data-cart-id")}).get().join(",");
			selectedSum(selectIds, function(){
				$(_this).addClass("selected");
				cartList.children("li").not(".disabled").addClass("selected");
			});
		}
	});
	//商品数量编辑器
	$(document).on("click", ".amount-reduce", function(){
		var input = $(this).next("input");
		var inputData = input.data("inputData");
		if(inputData.disabled||$(this).is(".dis")){
			return false;
		}else{
			var m = input.val()||0;
			m--;
			inputData.amount = m;
			input.data("inputData", JSON.stringify(inputData)).trigger("change");
		}		
	}).on("click", ".amount-add", function(){
		var input = $(this).prev("input");
		var inputData = input.data("inputData");
		if(inputData.disabled||$(this).is(".dis")){
			return false;
		}else{
			var m = input.val()||0;
			m++;
			inputData.amount = m;
			input.data("inputData", JSON.stringify(inputData)).trigger("change");
		}
	}).on("change", ".amount-input", function(e,init){
		var _this = this;
		var inputData = $(this).data("inputData");
		var max = parseInt($(this).attr("size"))||199;
		var min = 1;
		var state = true;
		var curVal = $(this).val();
		var m = inputData.amount||curVal;//点加减号运算后的数量值，存储起来，等请求响应后显示
		var lastVal = inputData.lastVal||curVal;
		if($.isEmpty(m)||m===false){
			m = $(this).val()
		}else{
			m = parseInt(m);
		}
		if(m<min||m>max||isNaN(m)){
			state = false;
			m = lastVal;
		}
		if(m<max||m>min){
			$(this).siblings().removeClass("dis");
		}
		if(m==max){
			$(this).next().addClass("dis");
		}
		if(m==min){
			$(this).prev().addClass("dis");
		}
		var curLi = $(this).closest("li");
		if(!init&&state){
			inputData.disabled = true;//锁定编辑
			$(_this).data("inputData", JSON.stringify(inputData));//保存锁定状态
			cartProccess(changeNumUrl, {//发请求
				cartId: curLi.attr("data-cart-id"),//获取当前商品cartid
				number: m,//当前商品数量
				selectedIds: getSelected()//选中的商品id
			}, function(data){
				data.flag||$.alert(data.msg);//有错的报错
				inputData = {"disabled":false,"amount":false,"lastVal":m};//
				$(_this).val(data.number).data("inputData",JSON.stringify(inputData));//赋值并解锁编辑
				var li = $(_this).closest("li");//当前商品li
				li.find(".cart-sum i").text(data.sumPrice==0?(data.sumSd+"试豆"):("￥"+data.sumPrice));//更新价格
				li.find(".cart-sum-amount").text(data.number);//更新数量
				setSettle(data);//去结算
			});
		}else{
			lastVal>max&&(lastVal=max);
			inputData = {"disabled":false,"amount":false,"lastVal":lastVal};
			$(_this).val(m).data("inputData",JSON.stringify(inputData));
		}
	});
	//去结算
	$("#settleCart").on("click", function(){
		var cart_ids = getSelected();
		if(cart_ids==""){
			$.tips("请选择商品",3000);
			return false;
		}else{
			settleCart(cart_ids, function(){
				$("[name='cart_ids']").val(cart_ids).parent().submit();
			});
		}
		_hmt.push(['_trackEvent', '去结算WAP', 'click', '去结算WAP']);
	});
})
//获取选中商品id集合
function getSelected(){
	return $("#cartList li.selected").map(function(){return $(this).attr("data-cart-id")}).get().join(",")
}
//选中商品结算
function selectedSum(cartIds, callback){
	if(cartIds == '') {
		console.log("没有选中商品");
		resetCart()
	}else{
		cartProccess(settleCartUrl, {
			cart_ids: cartIds
		}, function(data){
			data.flag||$.each(data.msg, function(key){
				var product = $("[data-product-id='"+key+"']");
				product.children(".error").text(data.msg[key][0]);
			})
			$.isFunction(callback)&&callback(data);
			setSettle(data);//需要在请求结束并选中后再结算
		});
	}
}
//购物车数据处理
function cartProccess(url, data, callback){
	$.loader();
	$.doAjax({
		url: url,
		type: "post",
		data: data,
		success: function(data){
			$.loaded();
			$.isFunction(callback)&&callback(data)
		}
	})
}
//设置结算总结额
function setSettle(data){
	var orderAmount = "￥"+(data.order_amount||"0.00");
	var tryCoin = (data.try_coin||0)+"试豆";
	var selectedAmount = 0;
	$("#cartList li.selected").each(function(){
		selectedAmount += $(this).find(".amount-input").val()*1;
	});
	$("#settleNumber").text(selectedAmount);
	$("#settleAmount").text(orderAmount+"+"+tryCoin);
	$("#fullcut").text(data.fullcut||'');
	$("#reduceAmount").text("￥-"+(data.reduce_amount||"0.00"));
}
//购物车重置
function resetCart(){
	$("#fullcut").text(fullcut);
	$("#settleAmount").text("￥0.00+0试豆");
	$("#reduceAmount").text("￥-0.00");
	$("#settleNumber").text(0);
}
//结算购物车
function settleCart(cart_ids, callback){
	$.loader();
	$.doAjax({
		url: settleCartUrl,
		type: "post",
		data: {cart_ids: cart_ids},
		success: function(data){
			$.loaded();
			if(data.flag){
				$.isFunction(callback)&&callback(data);
			}else{
				var coinMsg = data.msg.ship_amount_try_coin;
				if(coinMsg){
					$.alert(coinMsg[0]);
					return false;
				}else{
					for(var m in data.msg){
						var product = $("[data-product-id='"+m+"']");
						if(product.size()>0){
							$.tips("商品信息变动，我们将为您更新数据");
							$.loader("数据跟新中...");
							setTimeout(function(){
								$.go(0)
							}, 3000);
						}else{
							$.alert(data.msg[m][0]);
						}
						break;
					}
				}
			}
		}
	});
}
//保存历史上一页
function savePrevPageUrl(url){
	//购物车入口：首页-分类-个人中心-商品详情-商品列表
	var cartEntrance = ["index", "category", "user-center", "goods-list", "goods-detail"];
	if($.isEmpty(url)){
		sessionStorage.prevPageUrl = "/";
		return false;
	}else{
		var type = url.replace("http://").split("/")[1];//入口分类
		$.each(cartEntrance, function(i){
			type==cartEntrance[i]&&(sessionStorage.prevPageUrl=url);
		})
	}
}
//获取历史上一页
function getPrevPageUrl(){
	return sessionStorage.prevPageUrl||-1;
}


















